package distributeTables

import (
	"context"
	"devops-super/api"
	"devops-super/api/clusters/v1"
	"devops-super/internal/dao"
	"devops-super/internal/model/do"
	"devops-super/internal/model/entity"
	"devops-super/internal/model/mymodel"
	"devops-super/internal/service"
	"devops-super/utility/util/arrayUtil"
	"errors"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/gtime"
	"time"
)

type sDistributeTables struct{}

func init() {
	service.RegisterDistributeTables(New())
}

func New() *sDistributeTables {
	return &sDistributeTables{}
}

// GetPageLst 分页获取分发表列表
func (*sDistributeTables) GetPageLst(ctx context.Context, in *v1.DistributeTablesGetPageLstReq) (out *api.PageLstRes[*mymodel.DistributeTableResponse], err error) {
	out = &api.PageLstRes[*mymodel.DistributeTableResponse]{}
	m := dao.AppDistributeTables.Ctx(ctx).Safe(true)

	isSuperDept, currentUser, _ := service.User().IsCurrentUserSuperDept(ctx)
	if !isSuperDept {
		m = m.Where(dao.AppDeptToServerRecord.Columns().DeptId, currentUser.DeptId)
	}
	if in.TimeBy != "" {
		m = m.Where(dao.AppDistributeTables.Columns().TimeBy, in.TimeBy)
	}
	if in.ServerKey != "" {
		m = m.Where(dao.AppDistributeTables.Columns().ServerKey, in.ServerKey)
	}
	if in.DeptId > 0 {
		m = m.Where(dao.AppDistributeTables.Columns().DeptId, in.DeptId)
	}
	// 按时间范围筛选
	if in.TimeRange != nil {
		if len(in.TimeRange) != 2 {
			return nil, gerror.NewCode(gcode.CodeInvalidParameter, "时间范围参数格式错误")
		}
		// 新增时间转换逻辑
		startTime, err := time.Parse(time.RFC3339, in.TimeRange[0])
		if err != nil {
			return nil, gerror.WrapCode(gcode.CodeInvalidParameter, err, "开始时间格式错误")
		}
		endTime, err := time.Parse(time.RFC3339, in.TimeRange[1])
		if err != nil {
			return nil, gerror.WrapCode(gcode.CodeInvalidParameter, err, "结束时间格式错误")
		}
		timeLayout := "2006-01-02 15:04:05"
		timeStr0 := startTime.Local().Format(timeLayout)
		timeStr1 := endTime.Local().Format(timeLayout)
		m = m.WhereBetween(dao.AppDeptToServerRecord.Columns().CreatedAt, timeStr0, timeStr1)
	}
	// 时间分片规则筛选
	//if timeBy := in.Wheres.Get("timeBy"); !timeBy.IsNil() {
	//	m = m.Where(dao.AppDistributeTables.Columns().TimeBy, timeBy.Int())
	//}

	// 分页查询原始实体
	var entities []*entity.AppDistributeTables
	if err = m.Offset(in.Offset()).Limit(in.Limit()).ScanAndCount(&entities, &out.Total, false); err != nil {
		return
	}

	deptIds := make([]int64, 0)
	for _, item := range entities {
		if !arrayUtil.IsExistsItem(item.DeptId, deptIds) {
			deptIds = append(deptIds, int64(item.DeptId))
		}
	}
	var deptResults []*entity.Dept
	_ = dao.Dept.Ctx(ctx).WhereIn(dao.Dept.Columns().Id, deptIds).Scan(&deptResults)

	// 转换为响应模型
	out.List = make([]*mymodel.DistributeTableResponse, len(entities))
	for i, e := range entities {
		deptName := ""
		for _, d := range deptResults {
			if d.Id == int(e.DeptId) {
				deptName = d.Name
			}
		}

		out.List[i] = &mymodel.DistributeTableResponse{
			Id:          e.Id,
			TimeBy:      e.TimeBy,
			TimeStart:   e.TimeStart,
			TimeEnd:     e.TimeEnd,
			ServerKey:   e.ServerKey,
			Table:       e.Table,
			Flag:        e.Flag,
			CreatedAt:   e.CreatedAt,
			UpdatedAt:   e.UpdatedAt,
			IsExpire:    e.IsExpire,
			ExpireTime:  e.ExpireTime,
			TotalAmount: e.TotalAmount,
			TotalSize:   e.TotalSize,
			DeptId:      e.DeptId,
			DeptName:    deptName,
		}
	}
	return
}

// GetOne 获取单条分发表
func (*sDistributeTables) GetOne(ctx context.Context, id int) (out *mymodel.DistributeTableResponse, err error) {
	one := &entity.AppDistributeTables{}
	err = dao.AppDistributeTables.Ctx(ctx).WherePri(id).Scan(one)
	if err != nil {
		return nil, err
	}
	if one == nil || one.Id == 0 {
		return nil, nil
	}

	// 转换为响应模型
	out = &mymodel.DistributeTableResponse{
		Id:          one.Id,
		TimeBy:      one.TimeBy,
		TimeStart:   one.TimeStart,
		TimeEnd:     one.TimeEnd,
		ServerKey:   one.ServerKey,
		Table:       one.Table,
		Flag:        one.Flag,
		CreatedAt:   one.CreatedAt,
		UpdatedAt:   one.UpdatedAt,
		IsExpire:    one.IsExpire,
		ExpireTime:  one.ExpireTime,
		TotalAmount: one.TotalAmount,
		TotalSize:   one.TotalSize,
		DeptId:      one.DeptId,
	}
	return
}

// Add 添加分发表
func (*sDistributeTables) Add(ctx context.Context, in *v1.DistributeTablesAddReq) (err error) {
	return
}

// Upt 更新分发表
func (*sDistributeTables) Upt(ctx context.Context, in *v1.DistributeTablesUptReq) (err error) {
	if in.ExpireTime-gtime.Now().Unix() < 3600 {
		err = errors.New("cannot update expire-time in 1 hour")
		return
	}
	var old *entity.AppDistributeTables
	err = dao.AppDistributeTables.Ctx(ctx).WherePri(in).Scan(&old)
	if err != nil {
		return
	}
	isSuperDept, currentUser, _ := service.User().IsCurrentUserSuperDept(ctx)
	if !isSuperDept && currentUser.DeptId != int(old.DeptId) {
		err = errors.New("permission denied")
		return
	}
	updata := do.AppDistributeTables{
		IsExpire:   in.IsExpire,
		ExpireTime: in.ExpireTime,
		UpdatedAt:  gtime.Now(),
	}
	m := dao.AppDistributeTables.Ctx(ctx).WherePri(in)
	_, err = m.Update(updata)
	if err != nil {
		return err
	}
	return
}

// Del 删除分发表
func (*sDistributeTables) Del(ctx context.Context, id int) (err error) {
	// 检查记录是否存在
	var row *entity.AppDistributeTables
	err = dao.AppDistributeTables.Ctx(ctx).WherePri(id).Scan(&row)
	if err != nil {
		return err
	}
	if row == nil || row.Id == 0 {
		return errors.New("record not found")
	}
	isSuperDept, currentUser, _ := service.User().IsCurrentUserSuperDept(ctx)
	if !isSuperDept && currentUser.DeptId != int(row.DeptId) {
		return errors.New("permission denied")
	}
	// 删物联网数据和波形
	err = service.Iotdata().DelByDistributeTableId(ctx, int64(id))
	if err != nil {
		return err
	}
	// 删除记录
	_, err = dao.AppDistributeTables.Ctx(ctx).WherePri(id).Delete()
	return
}

// GetOptions 获取分发表选项列表
func (*sDistributeTables) GetOptions(ctx context.Context, in *v1.DistributeTablesGetOptionsReq) (out *v1.DistributeTablesGetOptionsRes, err error) {
	out = &v1.DistributeTablesGetOptionsRes{}
	out.Options = make([]*api.FormOptionsItem, 0)

	// 默认字段设置
	keyField := dao.AppDistributeTables.Columns().Id
	labelField := dao.AppDistributeTables.Columns().Table
	if in.FieldKey != "" {
		keyField = in.FieldKey
	}
	if in.FieldLabel != "" {
		labelField = in.FieldLabel
	}

	// 查询选项数据
	var list []gdb.Record
	list, err = dao.AppDistributeTables.Ctx(ctx).
		Where(dao.AppDistributeTables.Columns().DeptId, in.DeptId).
		Fields(keyField, labelField).
		Group(keyField, labelField).
		Order(keyField, "desc").
		Limit(2000).
		All()
	if err != nil {
		return
	}

	// 转换选项格式
	for _, item := range list {
		out.Options = append(out.Options, &api.FormOptionsItem{
			Value: item[keyField],
			Label: item[labelField].String(),
		})
	}

	return
}
